package com.masterclient.app.modules.aftersale;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.Editable;
import android.text.Html;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eoner.baselibrary.bean.aftersale.ReturnGoodsBean;
import com.eoner.baselibrary.bean.personal.UploadImgBean;
import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselibrary.utils.StringsUtils;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.BaseActivity;
import com.eoner.common.config.Config;
import com.masterclient.app.R;
import com.masterclient.app.base.TipDialog;
import com.masterclient.app.modules.aftersale.adapter.PromotionNumAdapter;
import com.masterclient.app.modules.aftersale.contract.ReturnGoodsContract;
import com.masterclient.app.modules.aftersale.contract.ReturnGoodsPresenter;
import com.eoner.uikit.dialog.simple.ChooseHeadImgDialog;
import com.masterclient.app.widget.PriceIntegralLayout;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import top.zibin.luban.Luban;

import static com.masterclient.app.R.id.rl_plus;
import static com.masterclient.app.R.id.rl_reduce;
import static com.masterclient.app.modules.aftersale.AfterSaleDetailActivity.NEW_AFTERSALE;
import static com.masterclient.app.businessmodule.usermodule.userinfo.UserInfoActivity.IMAGE_PICKER;
import static com.masterclient.app.businessmodule.usermodule.userinfo.UserInfoActivity.REQUEST_CODE_SELECT;

/**
 * 作者：sean
 * 创建时间：2017/7/28 10:15
 * 功能说明：
 */

public class ReturnGoodsActivity extends BaseActivity<ReturnGoodsPresenter> implements ReturnGoodsContract.View {
    String product_id, order_id;

    ReturnGoodsBean.DataBean.ShProductBean shProductBean;
    @BindView(R.id.rl_back)
    RelativeLayout rlBack;
    @BindView(R.id.rl_head)
    RelativeLayout rlHead;
    @BindView(R.id.v_head)
    View vHead;
    @BindView(R.id.tv_return_reason)
    TextView tvReturnReason;
    @BindView(R.id.tv_reason)
    TextView tvReason;
    @BindView(R.id.rl_choose_reason)
    RelativeLayout rlChooseReason;
    @BindView(R.id.iv_reduce)
    ImageView ivReduce;
    @BindView(rl_reduce)
    RelativeLayout rlReduce;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.iv_plus)
    ImageView ivPlus;
    @BindView(rl_plus)
    RelativeLayout rlPlus;
    @BindView(R.id.ll_change_num)
    LinearLayout llChangeNum;
    @BindView(R.id.tv_most_num)
    TextView tvMostNum;
    @BindView(R.id.ll_num)
    LinearLayout llNum;
    @BindView(R.id.v_num)
    View vNum;
    @BindView(R.id.ll_price)
    PriceIntegralLayout llPrice;
    @BindView(R.id.tv_payment_name)
    TextView tvPaymentName;
    @BindView(R.id.et_third_return)
    EditText etThirdReturn;
    @BindView(R.id.tv_most_return)
    TextView tvMostReturn;

    @BindView(R.id.et_hb_return)
    EditText etHbReturn;
    @BindView(R.id.tv_mosthb_return)
    TextView tvMosthbReturn;

    @BindView(R.id.et_balance_return)
    EditText etBalanceReturn;
    @BindView(R.id.tv_mostbalance_return)
    TextView tvMostbalanceReturn;

    @BindView(R.id.et_desc)
    EditText etDesc;
    @BindView(R.id.tv_remark)
    TextView tvRemark;
    @BindView(R.id.image)
    ImageView image;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.rl_add_img)
    RelativeLayout rlAddImg;
    @BindView(R.id.gridLayout)
    GridLayout gridLayout;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    @BindView(R.id.tv_tag1)
    TextView tvTag1;
    @BindView(R.id.rl_third)
    RelativeLayout rlThird;
    @BindView(R.id.tv_hb_tag2)
    TextView tvHbTag2;
    @BindView(R.id.tv_tag2)
    TextView tvTag2;
    @BindView(R.id.rl_hb)
    RelativeLayout rlHb;
    @BindView(R.id.tv_cash_tag2)
    TextView tvCashTag2;
    @BindView(R.id.tv_tag3)
    TextView tvTag3;
    @BindView(R.id.rl_balance)
    RelativeLayout rlBalance;
    @BindView(R.id.ll_yfh)
    LinearLayout llYfh;
    @BindView(R.id.tv_shipment_choose)
    TextView tvShipmentChoose;
    @BindView(R.id.tv_shipment)
    TextView tvShipment;
    @BindView(R.id.rl_shipment_choose)
    RelativeLayout rlShipmentChoose;
    @BindView(R.id.rl_integral)
    RelativeLayout rlIntegral;
    @BindView(R.id.et_integral_return)
    EditText etIntegralReturn;
    @BindView(R.id.tv_mostintegral_return)
    TextView tvMostintegralReturn;
    @BindView(R.id.rl_integral_deduction)
    RelativeLayout rlIntegralDeduction;
    @BindView(R.id.et_integral_return_deduction)
    EditText etIntegralReturnDeduction;
    @BindView(R.id.tv_mostintegral_return_deduction)
    TextView tvMostintegralReturnDeduction;
    @BindView(R.id.tv_giveaway)
    TextView tvGiveaway;

    @BindView(R.id.recycler)
    RecyclerView recyclerPromotion;
    @BindView(R.id.layout_payment_method)
    RelativeLayout layoutPaymentMethod;

    @BindView(R.id.view_tip)
    View viewTip;
    @BindView(R.id.tv_refund_num)
    TextView tvRefundNum;
    @BindView(R.id.tv_refund_notice)
    TextView tvRefundNotice;

    @BindView(R.id.layout_freight)
    View layoutFreight;
    @BindView(R.id.tv_freight_price)
    PriceIntegralLayout tvFreightPrice;
    @BindView(R.id.tv_freight_desc)
    TextView tvFreightDesc;
    @BindView(R.id.tv_freight_check)
    CheckBox tvFreightCheck;


    private SetAliPayDialog returnDialog;
    double mostPay_price = 0, mostRedPack = 0, most_balance;
    private long mostIntegral = 0, mostIntegralDeduction = 0;
    private ReturnReasonDialog returnReasonDialog;
    private ReturnShipmentDialog returnShipmentDialog;
    ReturnGoodsBean.DataBean dataBean;


    private List<UploadImgBean.DataBean> images = new ArrayList<>();
    private List<File> fileList;
    int num = 1;
    int maxNum;

    private String resean_id, receive_status = "", refund_reason_id, refund_type_id;
    private ChooseHeadImgDialog headImgDialog;
    ImagePicker imagePicker;
    private static final int IMAGE_SIZE = 9;
    private double pay_price;
    private double redPack, balance;
    private long integral, integralDeduction;

    private String beforeStr;
    private String update = "", fromType, refund_type;
    private RxPermissions rxPermissions;
    private PromotionNumAdapter promotionNumAdapter;
    private int imageHeight;
    private List<ReturnGoodsBean.DataBean.ShReasonBean> reason;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_return_goods);
        ButterKnife.bind(this);
        reason = new ArrayList<>();
        update = getBundleString("update");
        product_id = getBundleString("product_id");
        order_id = getBundleString("order_id");
        tvRemark.setText(Html.fromHtml("<font color=#F23051>注：</font>支付仅支持原路返回；余额支付返还余额；支付宝或微信支付，返还至付款账户（如有混合支付，返还至各自账户内）。"));
        fromType = getBundleString("from_type");
        refund_type = getBundleString("refund_type");

        if (!TextUtils.isEmpty(refund_type) && "dispatched".equals(refund_type)) {
            layoutPaymentMethod.setVisibility(View.GONE);
        }

        if (TextUtils.isEmpty(fromType)) {
            fromType = "";
        }
        if ("purchase".equals(fromType)) {
            tvSubmit.setBackgroundResource(R.drawable.shape_round_ff6809);
        }
        mPresenter.setFromType(fromType);

        mPresenter.preAfterSale("refundApplyBase", product_id, update, order_id);

//        Utils.setDin(tvAllReturn,this);

        returnDialog = new SetAliPayDialog(mContext);
        rxPermissions = new RxPermissions(this);

        imageHeight = ((int) ((ScreenUtils.getScreenWidth() - ScreenUtils.dp2px(23)) / 4f)) - ScreenUtils.dp2px(9);
        headImgDialog = new ChooseHeadImgDialog(mContext, "上传图片", "相册", "拍照");
        headImgDialog.setOnChooseListener(new ChooseHeadImgDialog.OnChooseListener() {
            @Override
            public void album() {
                Intent intent = new Intent(mContext, ImageGridActivity.class);
                startActivityForResult(intent, IMAGE_PICKER);
            }

            @Override
            public void photo() {
                rxPermissions
                        .requestEach(Manifest.permission.CAMERA)
                        .subscribe(permission -> { // will emit 2 Permission objects
                            if (permission.granted) {
                                // `permission.name` is granted !
                                Intent intent = new Intent(mContext, ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                startActivityForResult(intent, REQUEST_CODE_SELECT);
                            } else if (permission.shouldShowRequestPermissionRationale) {
                                // Denied permission without ask never again
                            } else {
                                // Denied permission with ask never again
                                // Need to go to the settings
                            }
                        });
            }
        });

        imagePicker = ImagePicker.getInstance();
        imagePicker.setMultiMode(true);
        imagePicker.setSelectLimit(IMAGE_SIZE);

        etHbReturn.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
        etHbReturn.setFilters(new InputFilter[]{new MyInputFilter()});
        etHbReturn.addTextChangedListener(new MyTextWatcher());

        etThirdReturn.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
        etThirdReturn.setFilters(new InputFilter[]{new MyInputFilter()});
        etThirdReturn.addTextChangedListener(new MyTextWatcher());

        etBalanceReturn.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
        etBalanceReturn.setFilters(new InputFilter[]{new MyInputFilter()});
        etBalanceReturn.addTextChangedListener(new MyTextWatcher());

        etIntegralReturn.addTextChangedListener(new MyTextWatcher());
        etIntegralReturnDeduction.addTextChangedListener(new MyTextWatcher());

        recyclerPromotion.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }

            @Override
            public boolean canScrollHorizontally() {
                return false;
            }
        });
        ((SimpleItemAnimator) recyclerPromotion.getItemAnimator()).setSupportsChangeAnimations(false);
        promotionNumAdapter = new PromotionNumAdapter();
        recyclerPromotion.setAdapter(promotionNumAdapter);
        promotionNumAdapter.bindToRecyclerView(recyclerPromotion);

        promotionNumAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                ReturnGoodsBean.DataBean.ShGiveProducts data = promotionNumAdapter.getData().get(position);
                switch (view.getId()) {
                    case R.id.edit_num_reduce:
                        data.setSh_refund_qty((TextUtils.isEmpty(data.getSh_refund_qty()) || Integer.parseInt(
                                data.getSh_refund_qty()) < 1 ? 0 : Integer.parseInt(data.getSh_refund_qty()) - 1) + "");
                        break;
                    case R.id.edit_num_plus:
                        data.setSh_refund_qty(TextUtils.isEmpty(data.getSh_refund_qty()) ? "1" : (
                                Integer.parseInt(data.getSh_refund_qty()) + (Integer.parseInt(
                                        data.getSh_refund_qty()) < Integer.parseInt(data.getSh_qty_ordered()) ? 1 : 0) + ""));
                        break;
                }
                promotionNumAdapter.notifyItemChanged(position);
            }
        });

    }

    public class MyInputFilter implements InputFilter {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            if (source.equals(".") && dest.toString().length() == 0) {
                return "0.";
            }
            if (dest.toString().contains(".")) {
                int index = dest.toString().indexOf(".");
                int mlength = dest.toString().substring(index).length();
                if (mlength == 3) {
                    return "";
                }
            }
            return null;
        }
    }

    public class MyTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            double all_price = 0;
            String hb = etHbReturn.getText().toString().trim();
            String third = etThirdReturn.getText().toString().trim();
            String balance = etBalanceReturn.getText().toString().trim();
            String intergal = etIntegralReturn.getText().toString().trim();
            String intergalDeduction = etIntegralReturnDeduction.getText().toString().trim();
            if (hb.endsWith(".") || third.endsWith(".") || balance.endsWith(".")) return;

            if (!TextUtils.isEmpty(hb) && Double.parseDouble(hb) - mostRedPack > 0.009) {
                etHbReturn.setText(mostRedPack + "");
                etHbReturn.setSelection((mostRedPack + "").length());
                hb = mostRedPack + "";
            }
            if (!TextUtils.isEmpty(third) && Double.parseDouble(third) - mostPay_price > 0.009) {
                etThirdReturn.setText(mostPay_price + "");
                etThirdReturn.setSelection((mostPay_price + "").length());
                third = mostPay_price + "";
            }
            if (!TextUtils.isEmpty(balance) && Double.parseDouble(balance) - most_balance > 0.009) {
                etBalanceReturn.setText(most_balance + "");
                etBalanceReturn.setSelection((most_balance + "").length());
                balance = most_balance + "";
            }
            if (!TextUtils.isEmpty(intergal) && Long.parseLong(intergal) - mostIntegral >= 1) {
                etIntegralReturn.setText(mostIntegral + "");
                etIntegralReturn.setSelection((mostIntegral + "").length());
                intergal = mostIntegral + "";
            }
            if (!TextUtils.isEmpty(intergalDeduction) && Long.parseLong(intergalDeduction) - mostIntegralDeduction >= 1) {
                etIntegralReturnDeduction.setText(mostIntegralDeduction + "");
                etIntegralReturnDeduction.setSelection((mostIntegralDeduction + "").length());
                intergalDeduction = mostIntegralDeduction + "";
            }

            if (!TextUtils.isEmpty(hb) && (!hb.startsWith(".") || hb.endsWith("."))) {
                all_price += Double.valueOf(hb);
            }

            if (!TextUtils.isEmpty(third) && (!third.startsWith(".") || third.endsWith("."))) {
                all_price += Double.valueOf(third);
            }

            if (!TextUtils.isEmpty(balance) && (!balance.startsWith(".") || balance.endsWith("."))) {
                all_price += Double.valueOf(balance);
            }

            llPrice.setData((TextUtils.isEmpty(intergal) ? 0 : Long.parseLong(intergal)) +
                            (TextUtils.isEmpty(intergalDeduction) ? 0 : Long.parseLong(intergalDeduction)) + "",
                    StringsUtils.keep2num(String.valueOf(all_price)));
//            Utils.set_price_style(ReturnGoodsActivity.this,tvAllReturn,11,(TextUtils.isEmpty(intergal)?0:Long.parseLong(intergal))
//                    +(TextUtils.isEmpty(intergalDeduction)?0:Long.parseLong(intergalDeduction))+"",StringUtils.keep2num(String.valueOf(all_price)));

//            tvAllReturn.setText(StringUtils.keep2num(String.valueOf(all_price)) + ((TextUtils.isEmpty(intergal)||TextUtils.isEmpty(intergalDeduction)
//                    || (Long.parseLong(intergal)+Long.parseLong(intergalDeduction)) == 0) ? "" : ("+" + (Long.parseLong(intergal)+Long.parseLong(intergalDeduction)) + "金币")));
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    @Override
    protected void onPause() {
        hideSoftInput(etDesc);
        super.onPause();
    }

    @Override
    public void preAfterSaleInfo(ReturnGoodsBean.DataBean dataBean) {
        this.dataBean = dataBean;
        if (dataBean.getSh_product() != null) {
            shProductBean = dataBean.getSh_product();

            if (!TextUtils.isEmpty(dataBean.getActual_can_refund_notice()) ||
                    !TextUtils.isEmpty(dataBean.getRefund_notice())) {
                viewTip.setVisibility(View.VISIBLE);
                if (!TextUtils.isEmpty(dataBean.getActual_can_refund_notice())) {
                    tvRefundNum.setVisibility(View.VISIBLE);
                    tvRefundNum.setText(dataBean.getActual_can_refund_notice());
                } else {
                    tvRefundNum.setVisibility(View.GONE);
                }
                if (!TextUtils.isEmpty(dataBean.getRefund_notice())) {
                    tvRefundNotice.setVisibility(View.VISIBLE);
                    tvRefundNotice.setText(dataBean.getRefund_notice());
                } else {
                    tvRefundNotice.setVisibility(View.GONE);
                }
            }

            mostPay_price = Double.valueOf(shProductBean.getSh_should_pay_price());
            mostRedPack = Double.valueOf(shProductBean.getSh_bupiao());
            most_balance = Double.valueOf(shProductBean.getSh_balance());
            mostIntegral = Long.valueOf(shProductBean.getSh_integral());
            mostIntegralDeduction = Long.parseLong(shProductBean.getSh_integral_deduction());

            if (mostRedPack == 0) {
                rlHb.setVisibility(View.GONE);
            }
            if (mostPay_price == 0) {
                rlThird.setVisibility(View.GONE);
            }

            if (most_balance == 0) {
                rlBalance.setVisibility(View.GONE);
            }
            if (mostIntegral == 0) {
                rlIntegral.setVisibility(View.GONE);
            }
            if (mostIntegralDeduction == 0) {
                rlIntegralDeduction.setVisibility(View.GONE);
            }
            llYfh.setVisibility(View.VISIBLE);

            tvMostNum.setText("(最多" + dataBean.getSh_product().getSh_qty_ordered() + "件)");
            tvPaymentName.setText(dataBean.getSh_payment_name());

            if (dataBean.getSh_gift_is_sent_refund_remark() != null && dataBean.getSh_gift_is_sent_refund_remark().length() > 0) {
                tvGiveaway.setVisibility(View.VISIBLE);
                tvGiveaway.setText(dataBean.getSh_gift_is_sent_refund_remark());
            }
            if (dataBean.getSh_refund_remark() != null && dataBean.getSh_refund_remark().length() > 0)
                tvRemark.setText(Html.fromHtml("<font color=#F23051>注：</font>" + dataBean.getSh_refund_remark()));

            llPrice.setData(mostIntegral + mostIntegralDeduction + "", StringsUtils.keep2num((mostPay_price + mostRedPack + most_balance) + ""));
//            Utils.set_price_style(ReturnGoodsActivity.this,tvAllReturn,11,mostIntegral+mostIntegralDeduction+"",StringUtils.keep2num((mostPay_price + mostRedPack + most_balance)+""));

//            tvAllReturn.setText(StringUtils.keep2num(String.valueOf(mostPay_price + mostRedPack + most_balance)) + ((mostIntegral+mostIntegralDeduction) == 0 ? "" : ("+" + (mostIntegral+mostIntegralDeduction) + "金币")));
            tvMostReturn.setText("(最多" + (mostPay_price) + "元)");
            etThirdReturn.setText(dataBean.getSh_product().getSh_should_pay_price_avg());
            tvMosthbReturn.setText("(最多" + (mostRedPack) + "元)");
            etHbReturn.setText(dataBean.getSh_product().getSh_bupiao_avg());
            tvMostbalanceReturn.setText("(最多" + (most_balance) + "元)");
            etBalanceReturn.setText(dataBean.getSh_product().getSh_balance_avg());
//            tvRedpackReturn.setText("支付红包" + redPack + "元");
            tvMostintegralReturn.setText("(最多" + (mostIntegral) + ")");
            etIntegralReturn.setText(dataBean.getSh_product().getSh_integral_avg());
            tvMostintegralReturnDeduction.setText("(最多" + (mostIntegralDeduction) + ")");
            etIntegralReturnDeduction.setText(dataBean.getSh_product().getSh_integral_deduction_avg());
            maxNum = Integer.valueOf(dataBean.getSh_product().getSh_qty_ordered());

            ivReduce.setImageResource(R.mipmap.jian_cart);
            rlReduce.setBackgroundResource(R.drawable.sku_num_text_left_unclick);
            if (maxNum > 1) {
                ivPlus.setImageResource(R.mipmap.jia2_cart);
                rlPlus.setBackgroundResource(R.drawable.sku_num_text_right);
            } else {
                ivPlus.setImageResource(R.mipmap.jia_cart);
                rlPlus.setBackgroundResource(R.drawable.sku_num_text_right_unclick);
            }
            if (dataBean.getSh_refund_info() == null || TextUtils.isEmpty(dataBean.getSh_refund_info().getSh_qty_refunded())) {
                num = Integer.valueOf(dataBean.getSh_product().getSh_qty_ordered());
                tvNum.setText(dataBean.getSh_product().getSh_qty_ordered());
                changeReducePlus(Integer.valueOf(dataBean.getSh_product().getSh_qty_ordered()));
                caculatePrice();
            } else {
                num = Integer.valueOf(dataBean.getSh_refund_info().getSh_qty_refunded());
                tvNum.setText(dataBean.getSh_refund_info().getSh_qty_refunded());
                changeReducePlus(Integer.valueOf(dataBean.getSh_refund_info().getSh_qty_refunded()));
                caculatePrice();
            }
        }

        if (dataBean.getSh_refund_info() != null && !TextUtils.isEmpty(dataBean.getSh_refund_info().getSh_id())) {
            //设置原因
            for (ReturnGoodsBean.DataBean.ShReasonBean reason : (!TextUtils.isEmpty(refund_type) && "dispatched".equals(refund_type) ? dataBean.getSh_new_reason().getSh_return_refund_custody().getSh_no_received() : dataBean.getSh_new_reason().getSh_return_refund().getSh_is_received())) {
                if (reason.getSh_relation_id().equals(dataBean.getSh_refund_info().getSh_relation_id())) {
                    tvReason.setText(reason.getSh_reason_name());
                    resean_id = reason.getSh_relation_id();
                    refund_reason_id = reason.getSh_refund_reason_id();
                    refund_type_id = reason.getSh_refund_type_id();
                    break;
                }

            }

            for (ReturnGoodsBean.DataBean.ShReceiveStatusListBean receiveStatus : dataBean.getSh_receive_status_list()) {
                if (receiveStatus.getSh_status_id().equals(dataBean.getSh_refund_info().getSh_receive_status())) {
                    tvShipment.setText(receiveStatus.getSh_status_text());
                    receive_status = receiveStatus.getSh_status_id();
                    break;
                }
            }

            etDesc.setText(dataBean.getSh_refund_info().getSh_description());

            etThirdReturn.setText(dataBean.getSh_refund_info().getSh_amount());
            etHbReturn.setText(dataBean.getSh_refund_info().getSh_bupiao_amount());
            tvNum.setText(dataBean.getSh_refund_info().getSh_qty_refunded());
            etBalanceReturn.setText(dataBean.getSh_refund_info().getSh_balance_amount());
            etIntegralReturn.setText(dataBean.getSh_refund_info().getSh_integral());
            etIntegralReturnDeduction.setText(dataBean.getSh_refund_info().getSh_integral_deduction());
            //退快递费
            if (!TextUtils.isEmpty(dataBean.getSh_refund_info().getSh_is_refund_shipping())){
                tvFreightCheck.setChecked("1".equals(dataBean.getSh_refund_info().getSh_is_refund_shipping()));
            }
            if (dataBean.getSh_refund_info().getSh_images() != null && dataBean.getSh_refund_info().getSh_images().size() > 0) {
                int i = 1;
                for (ReturnGoodsBean.DataBean.ShRefundInfoBean.ShImagesBean imagesBean : dataBean.getSh_refund_info().getSh_images()) {
                    UploadImgBean.DataBean dataBean1 = new UploadImgBean.DataBean();
                    dataBean1.setSh_image_url(imagesBean.getSh_url());
                    dataBean1.setSh_name(imagesBean.getSh_url());
                    images.add(dataBean1);

                    if (IMAGE_SIZE > images.size()) {
                        rlAddImg.setVisibility(View.VISIBLE);
                    } else {
                        rlAddImg.setVisibility(View.GONE);
                    }

                    View imageItem = View.inflate(mContext, R.layout.item_img, null);
                    ImageView imageView = (ImageView) imageItem.findViewById(R.id.image);
                    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    imageView.getLayoutParams().height = imageHeight;
                    imageView.getLayoutParams().width = imageHeight;
                    ImageView iv_delete = (ImageView) imageItem.findViewById(R.id.iv_delete);
                    iv_delete.setTag(dataBean1.getSh_image_url());
                    iv_delete.setOnClickListener(v -> {
                        gridLayout.removeView(imageItem);
//                        if (IMAGE_SIZE > images.size()) {
                        rlAddImg.setVisibility(View.VISIBLE);
//                        }
                        removeImage((String) iv_delete.getTag());
                    });
                    ViewTransformUtil.glideImageView(ReturnGoodsActivity.this, dataBean1.getSh_image_url(), imageView, new Transformation[]{
                            new CenterCrop(), new RoundedCornersTransformation(ScreenUtils.dp2px(4), 0)}, R.mipmap.defaults);

                    gridLayout.addView(imageItem, gridLayout.getChildCount() - 1);
                    i++;
                }
            }
        }

        promotionNumAdapter.setNewData(dataBean.getSh_give_products());

        //退快递费
        ReturnGoodsBean.DataBean.ShRefundShipping refundShipping = dataBean.getSh_refund_shipping();
        if (refundShipping!=null&&!TextUtils.isEmpty(refundShipping.getSh_show_amount())){
            tvFreightPrice.setData("0",refundShipping.getSh_show_amount());
            SpannableString spannableString = new SpannableString(new StringBuffer("已支付¥").append(refundShipping.getSh_show_amount()).append("，仅支持全部退回").toString());
            spannableString.setSpan(new RelativeSizeSpan(0.73f), 3, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            tvFreightDesc.setText(spannableString);
            layoutFreight.setVisibility(!TextUtils.isEmpty(refundShipping.getSh_show_refund_shipping())&&"1".equals(
                    refundShipping.getSh_show_refund_shipping())?View.VISIBLE:View.GONE);
        }else {
            layoutFreight.setVisibility(View.GONE);
        }


    }

    @SuppressLint("CheckResult")
    @Override
    public void applyAfterSaleSuccess() {
        dismiss_progressDialog();
        returnDialog.dismiss();
        RxBus.$().post(Config.AFTERSALE_REFRESH);
        setResult(ChooseAfterSaleActivity.RESULT_SUCCESS);
        Observable.just("s").delay(1000, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(s -> {
            if ("purchase".equals(fromType)) {
                ARouter.getInstance().build(AroutePath.AFTER_SALE_PURCHASE_DETAIL_ACTIVITY)
                        .withString("order_product_id", product_id)
                        .withString("order_id", order_id).navigation();
            } else {
                startActivitry(AfterSaleDetailActivity.class, new String[][]{{"product_id", product_id}, {"order_id", order_id}, {"type", NEW_AFTERSALE}});
            }
            finish();
        });
    }

    @Override
    public void onUploadSuccess(UploadImgBean.DataBean dataBean) {
        if (images == null) {
            images = new ArrayList<>();
        }
        images.add(dataBean);
        if (IMAGE_SIZE <= images.size()) {
            rlAddImg.setVisibility(View.GONE);
        }
    }

    @Override
    public void showError(String msg) {
        dismiss_progressDialog();
        showToast(msg);
    }

    @Override
    public void showError(String code, String msg) {
        dismiss_progressDialog();
        if ("40000".equals(code)) {
            TipDialog tipDialog = new TipDialog(this, "温馨提示", msg, "确定", 1);
            tipDialog.show();
        } else {
            showToast(msg);
        }
    }

    @OnClick({rl_reduce, rl_plus, R.id.tv_submit, R.id.rl_shipment_choose, R.id.rl_choose_reason, R.id.rl_add_img,
            R.id.rl_back,R.id.layout_freight})
    void onClick(View view) {
        switch (view.getId()) {

            case R.id.layout_freight:
                tvFreightCheck.setChecked(!tvFreightCheck.isChecked());
                break;
            case R.id.rl_back:
                finish();
                break;
            case R.id.rl_add_img:
                if (images == null) {
                    imagePicker.setSelectLimit(IMAGE_SIZE);
                } else {
                    imagePicker.setSelectLimit(IMAGE_SIZE - images.size());
                }
                headImgDialog.show();
                break;
            case R.id.rl_shipment_choose:
                if (dataBean == null) return;
                returnShipmentDialog = new ReturnShipmentDialog(mContext, dataBean.getSh_receive_status_list());
                returnShipmentDialog.setOnConfirmListener(new ReturnShipmentDialog.OnConfirmListener() {
                    @Override
                    public void onConfirm(String id, String reason) {
                        receive_status = id;
                        tvShipment.setText(reason);
                    }
                });
                returnShipmentDialog.show();
                break;
            case R.id.rl_choose_reason:
                if (dataBean != null) {
                    if (!TextUtils.isEmpty(refund_type) && "dispatched".equals(refund_type)) {
                        reason = dataBean.getSh_new_reason().getSh_return_refund_custody().getSh_no_received();
                    } else {
                        reason = dataBean.getSh_new_reason().getSh_return_refund().getSh_is_received();
                    }
                }
                if (reason == null || reason.size() <= 0) return;
                returnReasonDialog = new ReturnReasonDialog(mContext);
                returnReasonDialog.setOnConfirmListener(new ReturnReasonDialog.OnConfirmListener() {
                    @Override
                    public void onConfirm(int index) {
                        resean_id = reason.get(index).getSh_relation_id();
                        refund_reason_id = reason.get(index).getSh_refund_reason_id();
                        refund_type_id = reason.get(index).getSh_refund_type_id();
                        tvReason.setText(reason.get(index).getSh_reason_name());
                    }
                });
                returnReasonDialog.show();
                returnReasonDialog.setList(reason);
                break;
            case rl_reduce:
                if (num <= 1) {
//                    showToast("退货数量不能小于1件");
                } else {
                    num--;
                    tvNum.setText(num + "");
                }
                changeReducePlus(num);
                caculatePrice();
                break;
            case rl_plus:
                if (num >= maxNum) {
//                    showToast("退货数量不能大于购买数量");
                } else {
                    num++;
                    tvNum.setText(num + "");
                }
                changeReducePlus(num);
                caculatePrice();
                break;
            case R.id.tv_submit:
                if (dataBean == null) return;
                String returnMoney = etThirdReturn.getText().toString().trim();
                String returnHb = etHbReturn.getText().toString().trim();
                String returnBalance = etBalanceReturn.getText().toString().trim();
                String returnIntegral = etIntegralReturn.getText().toString().trim();
                String returnIntegralDeduction = etIntegralReturnDeduction.getText().toString().trim();

                List<String> imageStrs = new ArrayList<>();

                if (images != null) {
                    for (UploadImgBean.DataBean dataBean : images) {
                        imageStrs.add(dataBean.getSh_image_url());
                    }
                }

//                if (TextUtils.isEmpty(receive_status)) {
//                    showToast("请选择是否收到货");
//                    return;
//                }

                if (TextUtils.isEmpty(resean_id)) {
                    showToast("请选择退货退款原因");
                    return;
                }

                if (TextUtils.isEmpty(returnMoney) || TextUtils.isEmpty(returnHb)) {
                    showToast("金额不能为空");
                    return;
                }
                if (returnMoney.endsWith(".") || returnMoney.startsWith(".") || returnHb.endsWith(".")
                        || returnHb.startsWith(".") || returnBalance.startsWith(".") || returnBalance.endsWith(".")) {
                    showToast("请输入正确的金额格式");
                    return;
                }

                double hb = Double.valueOf(returnHb);
                double zfb = Double.valueOf(returnMoney);
                double bala = Double.valueOf(returnBalance);
                long integral = Long.valueOf(returnIntegral);
                long integralDeduction = Long.parseLong(returnIntegralDeduction);

//                if (zfb > mostPay_price) {
//                    showToast("请输入正确的退款金额");
//                    return;
//                }
//                if (hb > mostRedPack) {
//                    showToast("请输入正确的向日葵币金额");
//                    return;
//                }
//
//                if (bala > most_balance) {
//                    showToast("请输入正确的现金账户金额");
//                    return;
//                }
                if (integral > mostIntegral) {
                    showToast("请输入正确的金币兑换");
                    return;
                }
                if (integralDeduction > mostIntegralDeduction) {
                    showToast("请输入正确的金币抵扣");
                    return;
                }
                llPrice.setData(integral + integralDeduction + "", StringsUtils.keep2num((hb + zfb + bala) + ""));
//                Utils.set_price_style(ReturnGoodsActivity.this,tvAllReturn,11,integral+integralDeduction+"",StringUtils.keep2num((hb + zfb + bala)+""));

//                tvAllReturn.setText(StringUtils.keep2num((hb + zfb + bala)+"") + "" + ((integral+integralDeduction) == 0 ? "" : ("+" + (integral+integralDeduction) + "金币")));

//                if (isFastClick()) {
//                    showToast("操作过于频繁，请稍后再试");
//                    return;
//                }
                Map<String, String> giveProducts = null;
                if (dataBean.getSh_give_products() != null && dataBean.getSh_give_products().size() > 0) {
                    giveProducts = new HashMap<>();
                    for (ReturnGoodsBean.DataBean.ShGiveProducts bean : dataBean.getSh_give_products()) {
                        giveProducts.put(bean.getSh_id(), bean.getSh_refund_qty());
                    }
                }
                show_progressDialog();
                mPresenter.applyAfterSale(returnIntegral, receive_status, returnBalance, returnHb, etDesc.getText().toString().trim(),
                        imageStrs, product_id, String.valueOf(num), resean_id, !TextUtils.isEmpty(refund_type) && "dispatched"
                                .equals(refund_type) ? "3" : "1", returnMoney, update, order_id,
                        returnIntegralDeduction, "", "refundApplyPut", giveProducts, refund_reason_id, refund_type_id,
                        layoutFreight.getVisibility()!=View.VISIBLE?"":(tvFreightCheck.isChecked()?"1":"0"));

                break;
        }
    }

    private void changeReducePlus(Integer num) {

        ivReduce.setImageResource(R.mipmap.jian2_cart);
        rlReduce.setBackgroundResource(R.drawable.sku_num_text_left);
        ivPlus.setImageResource(R.mipmap.jia2_cart);
        rlPlus.setBackgroundResource(R.drawable.sku_num_text_right);

        if (num <= 1) {
            ivReduce.setImageResource(R.mipmap.jian_cart);
            rlReduce.setBackgroundResource(R.drawable.sku_num_text_left_unclick);
        }
        if (num >= maxNum) {
            ivPlus.setImageResource(R.mipmap.jia_cart);
            rlPlus.setBackgroundResource(R.drawable.sku_num_text_right_unclick);
        }
    }


    List<File> imageFileList;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {//相册
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                uploadImages(images);
            } else if (data != null && requestCode == REQUEST_CODE_SELECT) {//拍照
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                uploadImages(images);
            }
        }
    }

    @SuppressLint("CheckResult")
    private void uploadImages(ArrayList<ImageItem> images) {
        List<File> files = new ArrayList<>();
        for (ImageItem item : images) {
            File imgFile = new File(item.path);
            files.add(imgFile);
        }
//                mPresenter.uploadImage(files,"customer");
        if (files.size() > 0) {
            if (imageFileList == null) {
                imageFileList = new ArrayList<>();
            }
            //压缩并更新视图,上传图片
            Observable.fromIterable(files).map(new Function<File, File>() {
                @Override
                public File apply(@NonNull File file) throws Exception {
                    if (file != null) {
                        return Luban.with(mContext).load(file).get();
                    }
                    return null;
                }
            }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<File>() {
                @Override
                public void accept(@NonNull File file) throws Exception {
                    if (file != null) {
                        imageFileList.add(file);

                        if (IMAGE_SIZE <= imageFileList.size()) {
                            rlAddImg.setVisibility(View.GONE);
                        } else {
                            rlAddImg.setVisibility(View.VISIBLE);
                        }
                        View imageItem = View.inflate(mContext, R.layout.item_img, null);
                        ImageView imageView = (ImageView) imageItem.findViewById(R.id.image);
                        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                        imageView.getLayoutParams().height = imageHeight;
                        imageView.getLayoutParams().width = imageHeight;
                        ImageView iv_delete = (ImageView) imageItem.findViewById(R.id.iv_delete);
                        iv_delete.setTag(file.getName() + ".jpeg");
                        iv_delete.setOnClickListener(v -> {
                            gridLayout.removeView(imageItem);
                            imageFileList.remove(file);
//                            if (IMAGE_SIZE > imageFileList.size()) {
                            rlAddImg.setVisibility(View.VISIBLE);
//                            }
                            removeImage((String) iv_delete.getTag());
                        });

                        gridLayout.addView(imageItem, gridLayout.getChildCount() - 1);
                        ViewTransformUtil.glideImageView(ReturnGoodsActivity.this, file.toURI().toURL().toString(), imageView, new Transformation[]{
                                new CenterCrop(), new RoundedCornersTransformation(ScreenUtils.dp2px(4), 0)}, R.mipmap.defaults);

//                        Glide.with(ReturnGoodsActivity.this).load(file)
//                                .apply(new RequestOptions().placeholder(R.mipmap.defaults).error(R.mipmap.defaults)).into(imageView);
//                        App.picasso.load(file).fit().into(imageView);
                        mPresenter.uploadImage(file, "review ", file.getName() + ".jpeg");
                    }
                }
            });
        }
    }

    private void removeImage(String name) {
        int p = -1;
        for (int i = 0; i < images.size(); i++) {
            if (name.equals(images.get(i).getSh_name())) {
                p = i;
                break;
            }
        }

        if (p > -1) {
            images.remove(p);
        }
    }

    private void caculatePrice() {
        if (shProductBean == null) return;
        if (num == Long.parseLong(shProductBean.getSh_qty_ordered())) {
            pay_price = Double.valueOf(shProductBean.getSh_should_pay_price());
            redPack = Double.valueOf(shProductBean.getSh_bupiao());
            balance = Double.valueOf(shProductBean.getSh_balance());
            integral = Long.valueOf(shProductBean.getSh_integral());
            integralDeduction = Long.parseLong(shProductBean.getSh_integral_deduction());
        } else {
            pay_price = Double.valueOf(shProductBean.getSh_should_pay_price_avg()) * num;
            redPack = Double.valueOf(shProductBean.getSh_bupiao_avg()) * num;
            balance = Double.valueOf(shProductBean.getSh_balance_avg()) * num;
            integral = Long.valueOf(shProductBean.getSh_integral_avg()) * num;
            integralDeduction = Long.parseLong(shProductBean.getSh_integral_deduction_avg()) * num;
        }


        mostRedPack = redPack;
        mostPay_price = pay_price;
        most_balance = balance;
        mostIntegral = integral;
        mostIntegralDeduction = integralDeduction;
        tvMostReturn.setText("(最多" + StringsUtils.keep2num(String.valueOf(pay_price)) + "元)");
        tvMosthbReturn.setText("(最多" + StringsUtils.keep2num(String.valueOf(redPack)) + "元)");
        tvMostbalanceReturn.setText("(最多" + StringsUtils.keep2num(String.valueOf(balance)) + "元)");
        tvMostintegralReturn.setText("(最多" + integral + ")");
        tvMostintegralReturnDeduction.setText("(最多" + integralDeduction + ")");

        etThirdReturn.setText(StringsUtils.keep2num(String.valueOf(pay_price)) + "");
        etHbReturn.setText(StringsUtils.keep2num(String.valueOf(redPack)) + "");
        etBalanceReturn.setText(StringsUtils.keep2num(String.valueOf(balance)) + "");
        etIntegralReturn.setText(integral + "");
        etIntegralReturnDeduction.setText(integralDeduction + "");

        llPrice.setData(integral + integralDeduction + "", StringsUtils.keep2num((pay_price + redPack + balance) + ""));
//        Utils.set_price_style(ReturnGoodsActivity.this,tvAllReturn,11,integral+integralDeduction+"",StringUtils.keep2num((pay_price + redPack + balance)+""));

//        tvAllReturn.setText(StringUtils.keep2num((pay_price + redPack + balance) + "") + ((integral+integralDeduction) == 0 ? "" : ("+" + (integral+integralDeduction) + "金币")));


    }
}
